﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace BabushkaServer
{
    class Program
    {
        static void Main(string[] args)
        {
            
        }
    }
    class Server
    {
        TcpListener listener;
        Thread t;
        List<Socket> clients;
        public Server(int port, System.Net.IPAddress localIP)
        {
            listener = new TcpListener(localIP, port);
            t = new Thread(Listen);
            clients = new List<Socket>();
            t.Start();
        }
        public void Start()
        {
            if (IsRunning) return;
            IsRunning = true;
        }
        public void Stop()
        {
            if (!IsRunning) return;
            IsRunning = false;
        }
        public bool IsRunning { get; private set; }
        private void Listen()
        {
            while (true)
            {
                Thread.Sleep(150);

                if (!IsRunning || !listener.Pending())
                    continue;
                var s = listener.AcceptSocket();
                clients.Add(s);
                ClientReceived(this, s);
            }
        }
        ~Server()
        {
            Stop();
            t.Abort();
            foreach (var s in clients)
                s.Close();
        }
        public event ClientHandler ClientReceived;
        public event ClientHandler ClientDisconnected;
        public delegate void ClientHandler(Server server, Socket client);
    }
}
